#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "kp_base_type.h"
#include "iot_fan_motor.h"
#include "kp_pwm.h"

#define MOTOR_IO_GPIO_02  2
#define MOTOR_PWM_PORT_02 2
#define MOTOR_PWM_CLOCK_TYPE  0
#define MOTOR_PWM_CLOCK_160M  160000000
#define freq 2442  //min


/* 初始化电机模块 */
void AgricultureMotorInit(void)
{
    /* 电机接在GPIO-02引脚，初始化GPIO-02引脚 */
    u32 ret = IoTGpioInit(MOTOR_IO_GPIO_02);
	if(ret != KP_ERR_SUCCESS){ 
        printf("IoTGpioInit failed :%#x \r\n",ret);
		return;
    }

	/* 设置复用为PWM功能 */
	ret = IoTGpioSetFunc(MOTOR_IO_GPIO_02, IOT_GPIO_FUNC_GPIO_2_PWM2_OUT);
	if(ret != KP_ERR_SUCCESS){ 
        printf("IoTGpioSetFunc failed :%#x \r\n",ret);
		return;
    }

    /* PWM初始化 */
    ret = PwmDeinit(MOTOR_PWM_PORT_02);
    if(ret != KP_ERR_SUCCESS){ 
        printf("PwmDeinit failed :%#x \r\n",ret);
		return;
    }

    ret = PwmInit(MOTOR_PWM_CLOCK_TYPE, MOTOR_PWM_PORT_02);
    if(ret != KP_ERR_SUCCESS){ 
        printf("PwmInit failed :%#x \r\n",ret);
		return;
    }
	
	printf("----- AgricultureMotorInit success! -----\r\n");
}


/* 电机控制转动 */
void AgricultureMotorCtrl(motor_speed_level state)
{
    /* 初始化变量 */
    u32 ret = 0;

	switch (state) {
		case MOTOR_SPEED_LEVEL_0:
			/* 关闭电机 */
	        ret = PwmStop(MOTOR_PWM_PORT_02); 
	        if (ret != KP_ERR_SUCCESS) { 
	            printf("PwmStop failed ret : %#x \r\n", ret);
				return;
	        }
		    printf("stop motor \r\n");
            return;
		case MOTOR_SPEED_LEVEL_1:
			/* 一档风扇 */
		    //ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, PWM_DUTY_MAX * MOTOR_SPEED_LEVEL_1 / MOTOR_SPEED_LEVEL_MAX, freq);
			ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, 25, freq);
			if (ret != KP_ERR_SUCCESS) {
				printf("PwmStart failed ret : %#x \r\n", ret);
				return;
			}
			printf("start motor level 1 \r\n");
			return;
		case MOTOR_SPEED_LEVEL_2:
			/* 二档风扇 */
		    //ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, PWM_DUTY_MAX * MOTOR_SPEED_LEVEL_2 / MOTOR_SPEED_LEVEL_MAX, freq);
			ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, 50, freq);
			if (ret != KP_ERR_SUCCESS) {
				printf("PwmStart failed ret : %#x \r\n", ret);
				return;
			}
			printf("start motor level 2 \r\n");
			return;
		case MOTOR_SPEED_LEVEL_3:
			/* 三档风扇 */
		    //ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, PWM_DUTY_MAX * MOTOR_SPEED_LEVEL_3 / MOTOR_SPEED_LEVEL_MAX, freq);
			ret = PwmStart(MOTOR_PWM_PORT_02, MOTOR_PWM_CLOCK_160M, 75, freq);
			if (ret != KP_ERR_SUCCESS) {
				printf("PwmStart failed ret : %#x \r\n", ret);
				return;
			}
			printf("start motor level 3 \r\n");
			return;
		default:
			/* 无效风扇转速 */
			printf("invalid motor level \r\n");
			return;
	}
}

